package com.cqs.example.io.serial.utils;

import com.alibaba.fastjson.util.IOUtils;

import java.io.*;

/**
 * @Author lixw
 * @Date 7/21/20 12:01 AM
 */
public class JDKSerializer {

    public static byte[] jdkSerializer(Serializable serializable) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(bos);
            oos.writeObject(serializable);
            oos.flush();
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            IOUtils.close(oos);
            IOUtils.close(bos);
        }
    }

    public static <T extends Serializable> T jdkDeserializer(byte[] data,Class<T> type){
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ObjectInputStream bis = null;
        try {
            bis = new ObjectInputStream(bais);
            return (T) bis.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }finally {
            IOUtils.close(bis);
            IOUtils.close(bais);
        }
    }

}
